package ink.feny.controller;

import cn.hutool.crypto.SecureUtil;
import ink.feny.vo.UserRegisterVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * 用户 Controller
 * @author Feny
 * @date Created in 2021/4/29
 */
@Api(tags = "用户信息API")
@Validated
@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @ApiOperation("用户注册")
    @PostMapping("register")
    public String register(@Valid @RequestBody UserRegisterVO vo) {
        String sql = "INSERT INTO `tb_user`(`username`, `password`, `create_time`) " +
                "VALUES (?, ?, ?)";
        int update = jdbcTemplate.update(sql, vo.getUsername(),
                SecureUtil.md5(vo.getPassword()), LocalDateTime.now());
        if (update > 0) {
            return "注册成功";
        }
        return "注册失败";
    }

    @ApiOperation("用户信息")
    @GetMapping("{userId}")
    public List<Map<String, Object>> getUserById(@NotBlank(message = "userId不能为空")
                                                 @PathVariable("userId") String userId) {
        String sql = "select * from tb_user where id = ?";
        return jdbcTemplate.queryForList(sql, userId);
    }
}
